#!/usr/bin/env python
"""Auto-generate PEP 0 (PEP index).

Generating the PEP index is a multi-step process.  To begin, you must first
parse the PEP files themselves, which in and of itself takes a couple of steps:

    1. Parse metadata.
    2. Validate metadata.

With the PEP information collected, to create the index itself you must:

    1. Output static text.
    2. Format an entry for the PEP.
    3. Output the PEP (both by category and numerical index).

"""
from __future__ import absolute_import, with_statement
from __future__ import print_function

import sys
import os
import codecs

from operator import attrgetter

from pep0.output import write_pep0
from pep0.pep import PEP, PEPError

# S - Standards Track PEP ：跟踪Python中的新特性，就是描述新功能。
# I - Informational PEP ：说明Python中的某一个设计问题，就是指导方针、共识等内容，比如Python之禅、Python新版本的时间表等。
# P - Process PEP ：关于Python的提案，但不针对Python语言本身，就是Python开发中使用的工具、流程或者环境的更改。

# A - Accepted (Standards Track only) or Active proposal：已接受或活跃的提案
# D - Deferred proposal：被推迟的提案
# F - Final proposal：最终的提案
# P - Provisional proposal：临时的提案
# R - Rejected proposal：被拒绝的提案
# S - Superseded proposal：被取代的提案
# W - Withdrawn proposal：被撤回的提案


def main(argv):
    if not argv[1:]:
        path = './peps/'
    else:
        path = argv[1]

    peps = []
    if os.path.isdir(path):
        for file_path in os.listdir(path):
            if file_path.startswith('pep-0000.'):
                # print('IndexFile:', file_path)
                continue
            abs_file_path = os.path.join(path, file_path)
            if not os.path.isfile(abs_file_path):
                # print('NotFile:', abs_file_path)
                continue
            if file_path.startswith("pep-") and file_path.endswith((".txt", "rst")):
                # print(file_path.center(100, '='))
                with codecs.open(abs_file_path, 'r', encoding='UTF-8') as pep_file:
                    try:
                        pep = PEP(pep_file)
                        # print('ok')
                        if pep.number != int(file_path[4:-4]):
                            raise PEPError('PEP number does not match file name',
                                           file_path, pep.number)
                        # if pep.type_ != 'Standards Track':
                        #     print('NotS:', pep)
                        #     continue
                        # if pep.type_ == 'Process':
                        #     continue
                        if pep.status not in ('Accepted', 'Final'):
                            # print('NotAF:', pep)
                            continue
                        if 'Release Schedule' in pep.title:
                            continue
                        peps.append(pep)
                    except PEPError as e:
                        errmsg = "Error processing PEP %s (%s), excluding:" % \
                            (e.number, e.filename)
                        print(errmsg, e, file=sys.stderr)
                        sys.exit(1)
        peps.sort(key=attrgetter('number'))
    elif os.path.isfile(path):
        with open(path, 'r') as pep_file:
            peps.append(PEP(pep_file))
    else:
        raise ValueError("argument must be a directory or file path")

    for pep in peps:
        print(pep)

    # with codecs.open('pep-0000.rst', 'w', encoding='UTF-8') as pep0_file:
    #     write_pep0(peps, pep0_file)

if __name__ == "__main__":
    main(sys.argv)
